package org.xtframe.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.xtframe.entity.ServerData;
import org.xtframe.entity.UserData;
import org.xtframe.service.AjaxDataHandler;
import org.xtframe.service.AjaxDataHandlerException;
import org.xtframe.util.ContextUtil;
import org.xtframe.util.OsCacheUtil;
import org.xtframe.util.StringUtil;

@Service
@Scope("prototype")
public class ServerBreakDataHandler implements AjaxDataHandler {

	private final Log logger = LogFactory.getLog(getClass());

	public Map<String, Object> execute(String strData) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		try {
			UserData userData = ContextUtil.getCurrentUserData();
			if(userData == null){
				map.put(STATUS, false);
				map.put(LOGIN, true);
				throw new AjaxDataHandlerException("未登陆执行服务器刷新操作", 1);
			}
			ServerData serverData = ContextUtil.getServerData();
			
			JSONObject objJson = JSONObject.fromObject(strData);
			boolean flag = false;
			ArrayList<String> roleList = userData.getRoleList();
			for(String roleid : roleList){
				if(roleid.equals("admin")){
					flag = true;
					break;
				}
			}
			if(!(flag && (userData.getUser().getOrganId() == 1) && (userData.getUser().getJobId() == 1))){
				map.put(STATUS, false);
				map.put(LOGIN, false);
				throw new AjaxDataHandlerException("不具有服务器刷新的权限", 1);
			}
			
			String type = objJson.optString("type", "");
			if(StringUtil.isNullStr(type)) throw new AjaxDataHandlerException("没指明刷新对象的服务器刷新");
			if(type.equals("server")){
				map.put(STATUS, serverData.initAll());
			}
			else if(type.equals("role")){
				map.put(STATUS, serverData.initRole());
			}
			else if(type.equals("sql")){
				map.put(STATUS, serverData.initSQL());
			}
			else if(type.equals("menu")){
				map.put(STATUS, serverData.initMenu());
			}
			else if(type.equals("logic")){
				map.put(STATUS, serverData.initLogic());
			}
			else if(type.equals("res")){
				map.put(STATUS, serverData.initRes());
			}
			else if(type.equals("dictionary")){
				map.put(STATUS, serverData.initDictionary());
			}
			else if(type.equals("systemdata")){
				map.put(STATUS, serverData.initSystemData());
			}
			else if(type.equals("database")){
				map.put(STATUS, serverData.initDataBase());
			}
			else if(type.equals("oscache")){
				OsCacheUtil.flushAll();
				map.put(STATUS, true);
			}
		} catch(AjaxDataHandlerException ex){
			logger.warn(ex.toString());
			if(ex.getFlag() == 0){
				map.clear();
				map.put(STATUS, false);
			}
		} catch (Exception e) {
			logger.error(e.toString());
			map.clear();
			map.put(STATUS, false);
		}
		
		return map;
	}

}
